package com.gjp.filter;

import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.gjp.bean.Resource;
import com.gjp.service.ResourcesService;
import com.gjp.service.RolesService;
import com.gjp.service.UserService;

public class AnyRolesFilter extends AccessControlFilter {
	
	private String unauthorizedUrl = "/unauthorized.jsp";
	private String loginUrl = "/login.jsp";
	
	@Autowired
	UserService userService;
	@Autowired
	RolesService rolesService;
	@Autowired
	ResourcesService resourcesService;

	@Override
	protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object arg2) throws Exception {
		String[] roles = (String[]) arg2;
		if (roles == null) {
			return false;
		}
		Subject subject = getSubject(servletRequest, servletResponse);
		for (String role : roles) {
			if (subject.hasRole(role)) {
				return true;
			}
		}

		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
		Subject subject = getSubject(servletRequest, servletResponse);
		if (subject.getPrincipal() == null) {// 表示没有登录，重定向到登录页面
			System.out.println("no login ");
//			saveRequest(servletRequest);
			WebUtils.issueRedirect(servletRequest, servletResponse, loginUrl);
		} else {
			//取权限，校验权限
			String userName = subject.getPrincipal().toString();
	    	 List<Resource> resourceList = userService.getResourcesByUserName(userName);
	    	 if (resourceList == null || resourceList.size() == 0){
	    		 System.out.println("该人没有权限啊");
	    	 }
	    	 HttpServletRequest request = (HttpServletRequest) servletRequest;
	    	 String requestUri = request.getRequestURI();  
		     String contextPath = request.getContextPath();  
		     String url = requestUri.substring(contextPath.length());  
	    	 if (resourceList != null && resourceList.size() > 0) {
	    		 boolean flag = false;
	    		 for (Resource r : resourceList) {
	    			 if (r.getUrl().equals(url)){
	    				 flag = true;
	    				 break;
	    			 }
	    		 }
	    		 if (!flag) {
	    			 System.out.println("其实SecurityInterceptor已经拦截到了，只不过没有处理。");
	    		 }
	    	 }
		}
		return true;
	}

}
